package com.mall.util.distributed.raft.rpc;

import com.alipay.remoting.AsyncContext;
import com.alipay.remoting.BizContext;
import com.alipay.remoting.rpc.RpcServer;
import com.alipay.remoting.rpc.protocol.AsyncUserProcessor;
import com.mall.util.distributed.raft.consensus.Consensus;
import com.mall.util.distributed.raft.node.Node;
import com.mall.util.distributed.raft.rpc.message.RequestVote;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class DefaultRaftServer implements RaftServer {
    private final RpcServer rpcServer;

    @Autowired
    private Consensus consensus;

    public DefaultRaftServer(RpcServer rpcServer) {
        this.rpcServer = rpcServer;

        /* 注册请求处理 */
        rpcServer.registerUserProcessor(new AsyncUserProcessor<Request>() {
            @Override
            public void handleRequest(BizContext bizContext, AsyncContext asyncContext, Request request) {
                handlerRequest(request);
            }

            @Override
            public String interest() {
                return Request.class.getName();
            }
        });
    }

    @Override
    public void start() {
        var className = this.getClass().getName();
        log.info("{} starting", className);

        rpcServer.start();

        log.info("{} has start", className);
    }

    @Override
    public void stop() {
        var className = this.getClass().getName();
        log.info("{} stoping", className);

        rpcServer.stop();

        log.info("{} has stop", className);
    }

    @Override
    public Response handlerRequest(Request request) {
        var node = Node.getINSTANCE();

        log.info("{} reciv {}", node.getSelfAddress(), request.getCmd());

        if (request.getCmd() == Request.R_VOTE) {
            consensus.requestVote((RequestVote) request.getObj());
        } else if (request.getCmd() == Request.A_ENTRIES) {
        } else if (request.getCmd() == Request.CLIENT_REQ) {
        } else if (request.getCmd() == Request.CHANGE_CONFIG_REMOVE) {
        } else if (request.getCmd() == Request.CHANGE_CONFIG_ADD) {
        }
        return null;
    }
}
